// tslint:disable-next-line:no-var-requires
const apollo: any = require('ctrip-apollo');
import config from 'config';
import { resolve } from 'path';

// 获取config的绝对路劲
const basePath = resolve('./');

(process as any).env.ALLOW_CONFIG_MUTATIONS = true;

const apolloConfig = async () => {
  try {
    const { APOLLO_HOST, APOLLO_APPID, APOLLO_CLUSTER,
      APOLLO_PUBLIC_NAMESPACE, APOLLO_NAMESPACE } = process.env;
 
   const app = apollo({
     host: APOLLO_HOST || config.get('APOLLO_HOST'),
     appId: APOLLO_APPID || config.get('APOLLO_APPID'),
     cachePath: `${basePath}/config/apolloConfig`
   }).cluster(APOLLO_CLUSTER || config.get('APOLLO_CLUSTER'))
 
   const publicSpace = APOLLO_PUBLIC_NAMESPACE || config.get('APOLLO_PUBLIC_NAMESPACE');
   if(publicSpace) {
     await getNamespaceData(app, publicSpace);
   }
 
   await getNamespaceData(app, APOLLO_NAMESPACE || config.get('APOLLO_NAMESPACE'));
  } catch (error) {
    console.info('加载apollo配置出错:', error);
  }
}

async function getNamespaceData(app: any, name: string) {
  const namespace = app.namespace(name);
  const { _config } = await namespace.ready();

  namespace.on('updated', () => {
    Object.keys(_config).forEach((ele) => {
      // 解析对象
      _config[ele] = getJSONData(_config[ele]);
    });

    console.info('更新之后的远程配置:', _config);
    // 更新config配置
    config.util.extendDeep(config, config.util.toObject(_config));
  });

  namespace.on('delete', (ele: { key: any; value: any; }) => {
    console.info('删除的远程配置数据: ', ele);
    // 更新config配置
    config.util.extendDeep(config, config.util.toObject({ [ele.key]: '' }));
  });

  Object.keys(_config).forEach((ele) => {

    // 解析对象
    _config[ele] = getJSONData(_config[ele]);
  });

  // 加载远程配置
  config.util.extendDeep(config, config.util.toObject(_config));
}

// 转换json对象
function getJSONData(data: any) {
  try {
    return JSON.parse(data);
  } catch (e) {
    return data;
  }
}

export {
  config,
  apolloConfig
};
